/********* pay.m Cordova Plugin Implementation *******/

#import <Cordova/CDV.h>

#import "pay.h"
#import "VistaInAppPurchaseManager.h"

@interface pay ()<VistaInAppPurchaseManagerDelegate>
    
@property(nonatomic, strong)VistaInAppPurchaseManager * payManager;
@property (nonatomic, copy) NSString* callbackId;

@end
@implementation pay
- (void)pluginInitialize{
    self.payManager = [VistaInAppPurchaseManager sharedInstance];
    self.payManager.delegate = self;
}

- (void)successPluginResult:(NSDictionary*) message  callbackId:(NSString*)callbackId
{
    CDVPluginResult* pluginResult = nil;
    pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:message];
    [self.commandDelegate sendPluginResult:pluginResult callbackId:callbackId];

}
- (void)failurePluginResult:(NSDictionary*) message  callbackId:(NSString*)callbackId
{
    CDVPluginResult* pluginResult = nil;
    pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsDictionary:message];
    [self.commandDelegate sendPluginResult:pluginResult callbackId:callbackId];
}
- (NSDictionary *)getCommand:(CDVInvokedUrlCommand*)command
{
    if (command.arguments.count == 0) {
        [self failurePluginResult:@{@"error":@"没有d登录数据"} callbackId:command.callbackId];
    }
    return command.arguments[0];
}
    
- (void)pay:(CDVInvokedUrlCommand*)command
{
    NSDictionary * dic = [self getCommand:command];

    if (dic != nil && [[dic allKeys] containsObject:@"ProductID"]) {
        self.callbackId = command.callbackId;
        if ([[dic allKeys] containsObject:@"quantity"]) {
            self.payManager.quantity = [dic[@"quantity"] integerValue];
        }
        
        [self.payManager requestProductWithID:dic[@"ProductID"]];
    } else {
        [self failurePluginResult:@{@"failure":@""} callbackId:command.callbackId];
    }

}

#pragma mark -----   VistaInAppPurchaseManagerDelegate
    //购买商品回调
-(void)receiveProductInfo:(SKProduct *)product{
//    Hidden
    if (product != nil) {
        if (![self.payManager purchaseProudct:product]) {
            
            [self failurePluginResult:@{@"failure":@"",@"msg":@"您禁止了应用内购买权限,请到设置中开启"} callbackId:self.callbackId];

        }
        NSLog(@"SKProduct 描述信息%@", [product description]);
        NSLog(@"产品标题 %@" , product.localizedTitle);
        NSLog(@"产品描述信息: %@" , product.localizedDescription);
        NSLog(@"价格: %@" , product.price);
        NSLog(@"Product id: %@" , product.productIdentifier);
    }else{

        [self failurePluginResult:@{@"failure":@"",@"msg":@"无法连接App store!"} callbackId:self.callbackId];
    }
}
#pragma mark-VistaInAppPurchaseManagerDelegate
    //成功回调
    //附加：官方文档：向苹果校验支付结果https://developer.apple.com/library/content/releasenotes/General/ValidateAppStoreReceipt/Chapters/ValidateRemotely.html
-(void)successfulPurchaseOfId:(NSString *)productID andReceipt:(NSData *)transactionReceipt{
    NSLog(@"z成功");
    NSString *transactionReceiptString = [transactionReceipt base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];
    NSDictionary *dict = @{@"receipt-data":transactionReceiptString};
    [self successPluginResult:dict callbackId:self.callbackId];
//    NSString *str=[self conData11:dict];
//    //上传支付凭证到后台
//    NSDictionary *json = @{@"receipt":str};
//    NSDictionary *Json=@{@"code":@"5077",@"payload":[HHCommon convertToJsonData:json],@"token":personalToken};
//    [HTTPRequestManager postNetworkRequestWithUrlString:Com parameters:Json succeed:^(id data) {
//        if ([data[@"code"] integerValue]==0&&[data[@"payload"][@"status"] integerValue]==0) {
//            [PHAlertView showTitle:@"充值成功！" message:@"" surnBtnTitle:@"确定" result:nil];
//            [self loadmoney];
//            [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"receiptData"];
//        }else{
//            NSLog(@"%@",data[@"message"]);
//        }
//    } fail:^(NSError *error) {
//
//    }];
}
    //失败回调
- (void)failedPurchaseWithError:(NSString *)errorDescripiton {
    NSLog(@"购买失败");
    [self failurePluginResult:@{@"failure":@"",@"msg":@"购买失败"} callbackId:self.callbackId];

    
}

@end
